package mysqlinit

import (
	"api/appconfig"

	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	err error
	DB  *gorm.DB
)

func Init() {
	data := appconfig.Conf.Mysql
	sprintf := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", data.Username, data.Password, data.Host, data.Port, data.Database)

	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	DB, err = gorm.Open(mysql.Open(sprintf), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败")
	} else {
		logx.Info("数据库连接成功")
	}

	err = DB.AutoMigrate(&User{}, &HouseCover{}, &House{}, Order{})
	if err != nil {
		panic("迁移失败")
	} else {
		logx.Info("迁移成功")
	}
}
